package com.beiding;

import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.http.client.ClientHttpResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy

public class ZuulApplication extends ZuulFilter implements Filter {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String servletPath = req.getServletPath();
        if (servletPath.endsWith("/login") && !servletPath.equals("/ua/user/login")) {
            req.getRequestDispatcher("/ua/user/login").forward(request, response);
        } else if (servletPath.equals("/")) {

            //跳转到ua首页
            req.getRequestDispatcher("/ua/").forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }


    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 11;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();
        ClientHttpResponse zuulResponse = (ClientHttpResponse) ctx.get("zuulResponse");

        if (zuulResponse.getHeaders().getLocation() != null) {//如果含有重定向地址
            List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
            for (Pair<String, String> pair : zuulResponseHeaders) {
                if (pair.first().equals("Location")) {

                    //将所有的请求都
                    pair.setSecond("https" + pair.second().split("http")[1]);
                    break;
                }
            }

        }

        return null;
    }
}
